package com.edooteach.api.web.controller;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.edooteach.api.handler.FileHandler;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("/api/weapp/upload")
public class WechatUploadController {
	
	private static final Logger logger = LoggerFactory.getLogger(WechatUploadController.class);
	
	@Autowired
	private FileHandler fileHandler;
	
	/**
     * 
     * @param id
     * @param opengid
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult onUpload(HttpServletRequest request,
    						   @RequestParam("file") MultipartFile file,
    						   @RequestParam("filename") String filename) {
    	
    	HttpResult httpResult = new HttpResult();
    	
    	if(!file.isEmpty()) {
    		try {
				String filelink = fileHandler.saveFile(file, filename);
				return httpResult.success().data("filePtah", filelink);
			} catch (IllegalStateException | IOException e) {
				logger.error("save file error", e);
				throw BusinessException.newInstance("500", "保存文件失败");
			}
    	}
    	
    	throw BusinessException.newInstance("400", "获取文件失败");
    }
	
}
